package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.RoutePara;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ParkAdapter;
import flc.ast.databinding.ActivityParkBinding;
import flc.ast.utils.AMapUtil;
import flc.ast.utils.MyPoiOverlay;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.DistanceUtil;

public class ParkActivity extends BaseAc<ActivityParkBinding>{

    private AMap mAmap;
    //中心点经纬度
    private LatLng mCenterLatLng;
    //我的位置的经纬度
    private LatLng mMyLatLng;
    private MyPoiOverlay mPoiOverlay;
    //正在显示的点
    private Marker mShowMarker;
    private boolean isFist = true;
    private ParkAdapter parkAdapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //mapview
        mDataBinding.mapView.onCreate(savedInstanceState);
        mAmap = mDataBinding.mapView.getMap();

        //定位蓝点
        MyLocationStyle locationStyle = new MyLocationStyle();
        locationStyle.strokeColor(Color.parseColor("#00FFFFFF"));
        locationStyle.radiusFillColor(Color.parseColor("#00FFFFFF"));
        locationStyle.interval(2000);
        locationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        mAmap.setMyLocationStyle(locationStyle);
        mAmap.setMyLocationEnabled(true);

        //ui settings
        UiSettings uiSettings = mAmap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);
        uiSettings.setMyLocationButtonEnabled(true);
        uiSettings.setScaleControlsEnabled(true);

        //listener
        mAmap.addOnMyLocationChangeListener(onMyLocationChangeListener);
        mAmap.addOnCameraChangeListener(onCameraChangeListener);
        mAmap.addOnMarkerClickListener(onMarkerClickListener);
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_park;
    }

    @Override
    protected void initView() {
        mDataBinding.ivParkBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivClearText.setOnClickListener(this);
        mDataBinding.rvLocationList.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
        parkAdapter=new ParkAdapter();
        mDataBinding.rvLocationList.setAdapter(parkAdapter);
        parkAdapter.setOnItemClickListener(this);
        mDataBinding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                search(s.toString());
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivClearText:
                mDataBinding.etSearch.setText("");
                mDataBinding.rvLocationList.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        try {
            RoutePara routePara = new RoutePara();
            routePara.setStartPoint(mMyLatLng);
            routePara.setStartName(getString(R.string.my_location));
            routePara.setEndPoint(AMapUtil.convertToLatLng(parkAdapter.getItem(position).getLatLonPoint()));
            routePara.setEndName(parkAdapter.getItem(position).getTitle());
            AMapUtils.openAMapDrivingRoute(routePara, this);
        } catch (com.amap.api.maps.AMapException e) {
            ToastUtils.showShort(e.getMessage());
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        mDataBinding.mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mDataBinding.mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDataBinding.mapView.onDestroy();
        mAmap.removeOnMyLocationChangeListener(onMyLocationChangeListener);
        mAmap.removeOnCameraChangeListener(onCameraChangeListener);
        mAmap.removeOnMarkerClickListener(onMarkerClickListener);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mDataBinding.mapView.onSaveInstanceState(outState);
    }


    /**
     * 通过关键字搜索
     *
     * @param keyWord
     */
    private void search(final String keyWord) {
        if (TextUtils.isEmpty(keyWord)) {
            ToastUtils.showShort(getString(R.string.please_input_location));
            return;
        }
        PoiSearch.Query query = new PoiSearch.Query(keyWord, "150900", "");
        query.setPageSize(100);
        query.setPageNum(0);
        //设置查周边
        if (mCenterLatLng != null) {
            PoiSearch poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                @Override
                public void onPoiSearched(PoiResult poiResult, int retCode) {
                    if (retCode != AMapException.CODE_AMAP_SUCCESS) {
                        ToastUtils.showShort(getString(R.string.search_error));
                        mDataBinding.rvLocationList.setVisibility(View.GONE);
                        return;
                    }
                    if (poiResult == null || poiResult.getQuery() == null) {
                        ToastUtils.showShort(getString(R.string.not_search));
                        mDataBinding.rvLocationList.setVisibility(View.GONE);
                        return;
                    }

                    List<PoiItem> poiItemList = poiResult.getPois();
                    if (poiItemList == null || poiItemList.size() == 0) {
                        ToastUtils.showShort(getString(R.string.not_search));
                        mDataBinding.rvLocationList.setVisibility(View.GONE);
                        return;
                    }

                    if (mPoiOverlay != null) {
                        mPoiOverlay.removeFromMap();
                    }
                    mAmap.clear();
                    mPoiOverlay = new MyPoiOverlay(mAmap, poiItemList);
                    mPoiOverlay.addToMap();
                    mPoiOverlay.zoomToSpan();
                    parkAdapter.setList(poiItemList);
                    parkAdapter.notifyDataSetChanged();
                    mDataBinding.rvLocationList.setVisibility(View.VISIBLE);
                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {
                }
            });
            // 设置搜索区域为以lp点为圆心，其周围10公里范围
            LatLonPoint latLonPoint = new LatLonPoint(mCenterLatLng.latitude, mCenterLatLng.longitude);
            poiSearch.setBound(new PoiSearch.SearchBound(latLonPoint, 10000, true));
            // 异步搜索
            poiSearch.searchPOIAsyn();
        }
    }

    private void showMarker(Marker marker) {
        mShowMarker = marker;
        startNavi();
    }

    /**
     * 启动手机版高德应用进行路径规划
     */
    private void startNavi() {
        if (mShowMarker == null) return;
        try {
            RoutePara routePara = new RoutePara();
            routePara.setStartPoint(mMyLatLng);
            routePara.setStartName(getString(R.string.my_location));
            routePara.setEndPoint(mShowMarker.getPosition());
            routePara.setEndName(mShowMarker.getTitle());
            AMapUtils.openAMapDrivingRoute(routePara, this);
        } catch (com.amap.api.maps.AMapException e) {
            ToastUtils.showShort(e.getMessage());
        }
    }

    private AMap.OnMyLocationChangeListener onMyLocationChangeListener = new AMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            if (location == null) return;
            mMyLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            if (isFist) {
                isFist = false;
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                mCenterLatLng = latLng;
                float maxLevel = mAmap.getMaxZoomLevel();
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, maxLevel - 3);
                mAmap.moveCamera(cameraUpdate);
            }
        }
    };

    private AMap.OnCameraChangeListener onCameraChangeListener = new AMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
        }

        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {
            if (cameraPosition == null) return;
            if (cameraPosition.target != null) {
                mCenterLatLng = cameraPosition.target;
            }
        }
    };

    private AMap.OnMarkerClickListener onMarkerClickListener = new AMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            showMarker(marker);
            return true;
        }
    };
}